﻿#include "Internet.h"

#include <memory>
#include <string>
#include <format>

#pragma comment(lib,"Iphlpapi.lib") //需要添加Iphlpapi.lib库 
Internet::Internet()
{
    GetIfTable(this->_pIfTable, &this->_dwSize, TRUE);
    this->_pIfTable = reinterpret_cast<MIB_IFTABLE*>(new char[this->_dwSize]);
    this->_outSpeed = new char[20];
    this->_inSpeed = new char[20];
    this->loopTable();
}

void Internet::setInvokeFrame(USHORT frame)
{
    this->_invokeFrame = frame;
}

USHORT Internet::getInvokeFrame()
{
    return this->getInvokeFrame();
}

char* Internet::getOutSpeed() const
{
    return this->_outSpeed;
}

char* Internet::getInSpeed() const
{
    return this->_inSpeed;
}

void Internet::loopTable()
{
    GetIfTable(this->_pIfTable, &this->_dwSize, TRUE);
    const MIB_IFROW* pRow = nullptr;
    for(int i = 0; i < this->_pIfTable->dwNumEntries; ++i)
    {
        pRow = &(this->_pIfTable->table[i]);
        if(pRow->dwAdminStatus != 1)
        {
            continue;
        }
        if(pRow->dwOperStatus != IF_OPER_STATUS_OPERATIONAL)
        {
            continue;
        }
        if(pRow->dwOutOctets <= 0)
        {
            continue;
        }
        // 只找以太网和wifi
        if(pRow->dwType == IF_TYPE_ETHERNET_CSMACD || pRow->dwType == IF_TYPE_IEEE80211)
        {
            this->_lastOutOctets = pRow->dwOutOctets;
            this->_lastInOctets = pRow->dwInOctets;
            break;
        }
    }
}

void Internet::dealDifference(DWORD InDifference, DWORD outDifference) const
{
    double difference = InDifference*2/1024.0;
    std::string s = "下载: ↓ ";
    if(difference < 1024)
    {
        s += std::format("{:.2f}", difference);
        s+= "kB/s";
    }else
    {   

        difference/=1024.0;
        s += std::format("{:.2f}", difference);
        s+= "MB/s";
    }
    _memccpy(this->_inSpeed, s.c_str(), '\0', s.size() + 1);

    s = "上传: ↑ ";
    difference = outDifference*2/1024.0;
    if(difference < 1024)
    {
        s += std::format("{:.2f}", difference);
        s+= "kB/s";
    }else
    {
        difference/=1024.0;
        s += std::format("{:.2f}", difference);
        s+= "MB/s";
    }
    _memccpy(this->_outSpeed, s.c_str(), '\0', s.size() + 1);
}



